﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;

public partial class uMESCheckingPlanPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESResourceManagementBusiness bll = new uMESResourceManagementBusiness();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (Session["ResourceAddCheckPlan"] !=null)
            {
                Dictionary<string, string> para = new Dictionary<string, string>();
                BindFactory(para);
                BindTeamInfo(para);
                BindEmployeeInfo(para);
                BindCheckCycle();

                DataTable dt =(DataTable)Session["ResourceAddCheckPlan"];
                BindPageControl(dt);

                BindGridData();
            }
        }

    }

    #region 数据绑定

    /// <summary>
    /// 绑定分厂信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindFactory(Dictionary<string, string> para)
    {
        DataTable dt = bll.GetFactoryInfo(para);
        ddlFactory.DataTextField = "factoryname";
        ddlFactory.DataValueField = "factoryid";
        ddlFactory.DataSource = dt;
        ddlFactory.DataBind();
        ddlFactory.Items.Insert(0, "");
    }

    /// <summary>
    /// 绑定班组信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindTeamInfo(Dictionary<string, string> para)
    {
        DataTable dt = bll.GetTeamInfo(para);
        ddlTeam.DataTextField = "TeamName";
        ddlTeam.DataValueField = "TeamID";
        ddlTeam.DataSource = dt;
        ddlTeam.DataBind();
        ddlTeam.Items.Insert(0, "");
    }

    /// <summary>
    /// 绑定点检人信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindEmployeeInfo(Dictionary<string, string> para)
    {
        DataTable dt = bll.GetEmployeeInfo(para);
        ddlCheck.DataTextField = "fullname";
        ddlCheck.DataValueField = "employeeid";
        ddlCheck.DataSource = dt;
        ddlCheck.DataBind();
        ddlCheck.Items.Insert(0, "");
    }

    protected void BindCheckCycle()
    {
        ListItem item = new ListItem();
        item = new ListItem("周点检", "0");
        ddlCheckCycle.Items.Add(item);

        item = new ListItem("日点检", "1");
        ddlCheckCycle.Items.Add(item);

        item = new ListItem("临时点检", "2");
        ddlCheckCycle.Items.Add(item);

        ddlCheckCycle.Items.Insert(0, "");
    }
    protected void BindPageControl(DataTable dt)
    {
        if (!string.IsNullOrEmpty(dt.Rows[0]["description"].ToString()))
        {
            txtName.Text = dt.Rows[0]["description"].ToString();
        }


        if (!string.IsNullOrEmpty(dt.Rows[0]["resourcename"].ToString()))
        {
            txtNum.Text = dt.Rows[0]["resourcename"].ToString();
        }

        if (!string.IsNullOrEmpty(dt.Rows[0]["resourceid"].ToString()))
        {
            txtResourceID.Text = dt.Rows[0]["resourceid"].ToString();
        }

        if (!string.IsNullOrEmpty(dt.Rows[0]["assetnumber"].ToString()))
        {
            txtAssetNumber.Text = dt.Rows[0]["assetnumber"].ToString();
        }


        if (!string.IsNullOrEmpty(dt.Rows[0]["factoryid"].ToString()))
        {
            ddlFactory.SelectedValue = dt.Rows[0]["factoryid"].ToString();
        }

        if (!string.IsNullOrEmpty(dt.Rows[0]["teamid"].ToString()))
        {
            ddlTeam.SelectedValue = dt.Rows[0]["teamid"].ToString();
        }
    }

    protected void BindGridData()
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ResourceID", txtResourceID.Text);

        DataTable dt = bll.GetResourceCheckPlanInfo(para);
        ItemGrid.DataSource = dt;
        ItemGrid.DataBind();
    }
    #endregion

    #region 选中行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            txtCheckDate.Disabled = true;
     

            txtNotes.Text = string.Empty;
            if (e.Row.Cells.FromKey("notes").Value != null)
            {
                txtNotes.Text = e.Row.Cells.FromKey("notes").Text;
            }

            //if (e.Row.Cells.FromKey("factoryid").Value != null)
            //{
            //    ddlFactory.SelectedValue = e.Row.Cells.FromKey("factoryid").Text;
            //}

            //if (e.Row.Cells.FromKey("teamid").Value != null)
            //{
            //    ddlTeam.SelectedValue = e.Row.Cells.FromKey("teamid").Text;
            //}

            if (e.Row.Cells.FromKey("checkcycle").Value != null)
            {
                ddlCheckCycle.SelectedValue = e.Row.Cells.FromKey("checkcycle").Text;
            }

            if (e.Row.Cells.FromKey("plancheckerid").Value != null)
            {
                ddlCheck.SelectedValue = e.Row.Cells.FromKey("plancheckerid").Text;
            }

            if (e.Row.Cells.FromKey("plancheckdate").Value != null)
            {
                txtCheckDate.Value = Convert.ToDateTime(e.Row.Cells.FromKey("plancheckdate").Value).ToString("yyyy-MM-dd");
              
            }

        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    #endregion

    protected void ClearControlInfo()
    {
        txtCheckDate.Disabled = false;
        txtNotes.Text = string.Empty;
        txtCheckDate.Value = "";
        if (ddlCheckCycle.Items.Count>0)
        {
            ddlCheckCycle.SelectedIndex = 0;
        }

        if (ddlCheck.Items.Count > 0)
        {
            ddlCheck.SelectedIndex = 0;
        }
    }

    /// <summary>
    /// 确定按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            string strMessage = string.Empty;
            bool oResult;
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;

            if (activeRow == null)
            {
                oResult = SaveData(ref strMessage);
            }
            else
            {
                oResult = UpdateData(ref strMessage);
            }

            if (oResult == true)
            {
                BindGridData();
                ClearControlInfo();
            }
            ShowStatusMessage(strMessage, oResult);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 保存信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <returns></returns>
    protected bool SaveData(ref string strMessage)
    {
        bool blResult = true;
        strMessage = string.Empty;
        if (ddlCheckCycle.SelectedItem.Text=="")
        {
            strMessage = "点检周期不能为空！";
            blResult = false;
            return blResult;
        }

        if (txtCheckDate.Value == "")
        {
            strMessage = "点检时间不能为空！";
            blResult = false;
            return blResult;
        }

        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        //以字典形式传递参数
        Dictionary<string, object> para = new Dictionary<string, object>();
        DataSet ds = new DataSet();
        DataTable dtMain = new DataTable();
        dtMain.Columns.Add("ID");//表主键
        dtMain.Columns.Add("ResourceID");//设备ID
        dtMain.Columns.Add("ResourceName");//设备编号
        dtMain.Columns.Add("Description");//设备名称
        dtMain.Columns.Add("AssetNumber");//资产编号
        dtMain.Columns.Add("FactoryID");//所属分厂
        dtMain.Columns.Add("TeamID");//所属班组
        dtMain.Columns.Add("CheckCycle");//点检周期
        dtMain.Columns.Add("PlanCheckDate");//计划点检时间
        dtMain.Columns.Add("PlanCheckerID");//计划点检人
        dtMain.Columns.Add("Notes");//备注
        dtMain.Columns.Add("CreateDate");//创建时间
        dtMain.Columns.Add("CreaterID");//创建人ID
        dtMain.Columns.Add("Status");//状态
        dtMain.Columns.Add("NextCheckDate");//下次点检周期


        dtMain.Rows.Add();
        int intAddRow = dtMain.Rows.Count - 1;
        dtMain.Rows[intAddRow]["ID"] = Guid.NewGuid().ToString() + "㊣String";
        dtMain.Rows[intAddRow]["ResourceID"] = txtResourceID.Text + "㊣String";
        dtMain.Rows[intAddRow]["ResourceName"] = txtNum.Text + "㊣String";
        dtMain.Rows[intAddRow]["Description"] =txtName.Text + "㊣String";
        dtMain.Rows[intAddRow]["AssetNumber"]=txtAssetNumber.Text + "㊣String";
        dtMain.Rows[intAddRow]["FactoryID"]=ddlFactory.SelectedValue + "㊣String";
        dtMain.Rows[intAddRow]["TeamID"]=ddlTeam.SelectedValue + "㊣String";
        dtMain.Rows[intAddRow]["CheckCycle"]=ddlCheckCycle.SelectedValue + "㊣Integer";
        dtMain.Rows[intAddRow]["PlanCheckDate"]=txtCheckDate.Value + "㊣Date";
        dtMain.Rows[intAddRow]["PlanCheckerID"]=ddlCheck.SelectedValue + "㊣String";
        dtMain.Rows[intAddRow]["Notes"]=txtNotes.Text + "㊣String";
        dtMain.Rows[intAddRow]["CreateDate"]= DateTime.Now + "㊣Date";
        dtMain.Rows[intAddRow]["CreaterID"] = userInfo["EmployeeID"] + "㊣String";
        dtMain.Rows[intAddRow]["Status"] ="1" + "㊣String";
        dtMain.Rows[intAddRow]["NextCheckDate"]=""+"㊣Date";



        dtMain.Rows.Add();
        dtMain.Rows[dtMain.Rows.Count - 1]["ID"] = "" + "㊣String";
        ds.Tables.Add(dtMain);
        ds.Tables[ds.Tables.Count - 1].TableName = "ResourceCheckPlanInfo" + "㊣ID";
        //保存数据
        para.Add("dsData", ds);
       
        bool result = bll.SaveDataToDatabaseNew(para, out strMessage);
        return blResult;
    }

    protected bool UpdateData(ref string strMessage)
    {
        bool blResult = true;
        strMessage = string.Empty;
        try
        {
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            DataTable dtUpdate = new DataTable();
            dtUpdate.Columns.Add("TableName");
            dtUpdate.Columns.Add("ID");
            dtUpdate.Columns.Add("CheckCycle");
            dtUpdate.Columns.Add("PlanCheckDate");
            dtUpdate.Columns.Add("PlanCheckerID");
            dtUpdate.Columns.Add("Notes");

            dtUpdate.Rows.Add();
            int intUpdateRow = dtUpdate.Rows.Count - 1;
            dtUpdate.Rows[intUpdateRow]["TableName"] = "ResourceCheckPlanInfo";
            dtUpdate.Rows[intUpdateRow]["ID"] = activeRow.Cells.FromKey("ID").Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["CheckCycle"] = ddlCheckCycle.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["PlanCheckDate"] = txtCheckDate.Value + "㊣Date";
            dtUpdate.Rows[intUpdateRow]["PlanCheckerID"] = ddlCheck.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["Notes"] = txtNotes.Text + "㊣String";

            int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
            if (iResult == -1)
            {
                blResult = false;

            }

            return blResult;
        }
        catch (Exception ex)
        {
            blResult = false;
            strMessage = ex.Message;
        }
        return blResult;

    }

    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }

    /// <summary>
    /// 验证是否是正整数
    /// </summary>
    /// <param name="inString"></param>
    /// <returns></returns>
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }


    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            ShowStatusMessage("", true);
            BindGridData();
            ClearControlInfo();
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message,false);
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            if (activeRow==null)
            {
                ShowStatusMessage("请选择要删除的记录！", false);
                return;
            }

            DataTable dtUpdate = new DataTable();
            dtUpdate.Columns.Add("TableName");
            dtUpdate.Columns.Add("ID");
            dtUpdate.Columns.Add("Status");
  

            dtUpdate.Rows.Add();
            int intUpdateRow = dtUpdate.Rows.Count - 1;
            dtUpdate.Rows[intUpdateRow]["TableName"] = "ResourceCheckPlanInfo";
            dtUpdate.Rows[intUpdateRow]["ID"] = activeRow.Cells.FromKey("ID").Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["Status"] = "0" + "㊣String";

            string strMessage = string.Empty;
            int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
            if (iResult == -1)
            {
                ShowStatusMessage(strMessage, false);
                return;

            }
            ShowStatusMessage(strMessage, true);
            BindGridData();
            ClearControlInfo(); 
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

}